package com.kczd.jinlan.view;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kczd.jinlan.R;
import com.kczd.jinlan.SysApplication;
import com.kczd.jinlan.model.User;
import com.kczd.jinlan.utils.Config;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 登录页面
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG="RegisterActivity.class";
    String url = Config.net_addr + "login/login";

    private EditText phone;
    private EditText password;
    private TextView tv_forgetPswd;
    private ImageView mLogin;
    private ImageView mRegister;

    SweetAlertDialog pDialog = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        SysApplication.getInstance().addActivity(this);

        initViews();
    }

    private void initViews() {

        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);

        phone= (EditText) findViewById(R.id.et_phone);
        password= (EditText) findViewById(R.id.et_passwd);
        tv_forgetPswd= (TextView) findViewById(R.id.tv_forgetPswd);
        mLogin= (ImageView) findViewById(R.id.id_login);
        mRegister= (ImageView) findViewById(R.id.id_register);
        mRegister.setOnClickListener(this);
        mLogin.setOnClickListener(this);
        tv_forgetPswd.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.id_login:
                if (!subpre()){
                    new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("必填验证")
                            .setContentText("你是不是忘了填什么")
                            .show();
                    return;
                }else{
                    pDialog.show();
                    /**
                     * 访问服务器，执行操作
                     */
                    new Thread(){
                        @Override
                        public void run()
                        {
                            loginHandle();
                        }
                    }.start();
                }
                break;
            case R.id.id_register://注册
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
                finish();
                break;
            case R.id.tv_forgetPswd://忘记密码
                startActivity(new Intent(LoginActivity.this,forgetPwdActivity.class));
                finish();
                break;
        }
    }

    /**
     * 检测用户名和密码是否为空
     * @return
     */
    public boolean subpre(){
        String loginusername= phone.getText().toString();
        String paswd= password.getText().toString();

        if(loginusername.isEmpty() || paswd.isEmpty()){
            return false;
        }
        return true;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            SysApplication.getInstance().exit();
            System.exit(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 登录Net
     */
    public void loginHandle() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("mobile", phone.getText().toString())
                .add("password", password.getText().toString())
                .build();
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG,val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(Config.code.equals(jsonResult.getString("code"))){
                    pDialog.dismiss();
                    Config.user=new User();
                    Config.user.JsonTobject(jsonResult);
                    //永久化保存token
                    Config.saveObject(getBaseContext(),Config.user);
                    LoginActivity.this.finish();
                    Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                }else{
                    pDialog.dismiss();
                    new SweetAlertDialog(LoginActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("登陆失败")
                            .show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

}
